package com.mazaiting.uac.service.impl;

import com.mazaiting.common.core.domain.result.ResultCode;
import com.mazaiting.common.core.ex.exceptions.BaseException;
import com.mazaiting.common.core.ex.exceptions.BusinessException;
import com.mazaiting.common.core.utils.DateTimeUtil;
import com.mazaiting.rabbitmq.constant.MqConstant;
import com.mazaiting.rabbitmq.domain.info.MessageInfo;
import com.mazaiting.rabbitmq.service.IMqService;
import com.mazaiting.sms.constant.SmsConstant;
import com.mazaiting.sms.constant.SmsTemplateConstant;
import com.mazaiting.sms.domain.dto.SmsDto;
import com.mazaiting.sms.enums.SmsTypeEnum;
import com.mazaiting.uac.config.SmsProperties;
import com.mazaiting.uac.convert.ISmsConvert;
import com.mazaiting.uac.domain.vo.SmsVO;
import com.mazaiting.uac.service.ISmsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 短信验证码服务实现
 *
 * @author mazaiting
 * @create_time 2022/9/28 14:23
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ISmsServiceImpl implements ISmsService {

    private final IMqService mqService;

    private final ISmsConvert smsConvert;

    private final SmsProperties smsProperties;

    @Override
    public boolean sendLoginCode(Long t, SmsVO smsVO) throws BaseException {
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis - t > smsProperties.getTimeout()) {
            log.info("当前时间: {}, 获取登录短信验证码时间: {}",
                    DateTimeUtil.time2String(currentTimeMillis, DateTimeUtil.YYYY_MM_DD_HH_MM_SS_SSS),
                    DateTimeUtil.time2String(t, DateTimeUtil.YYYY_MM_DD_HH_MM_SS_SSS));
            return false;
        }
        // 判断类型是为登录
        if (!SmsTypeEnum.VERIFY_CODE_LOGIN.equals(smsVO.getType())) {
            throw new BusinessException(ResultCode.MSG_SMS_TYPE_ERROR);
        }
        // 设置消息发送实体
        MessageInfo<SmsDto> messageInfo = new MessageInfo<>(SmsConstant.EXCHANGE_SMS_LOGIN, SmsConstant.KEY_SMS_LOGIN);
        // 设置消息内容
        SmsDto smsDto = smsConvert.vo2Dto(smsVO);
        smsDto.setCode(SmsTemplateConstant.SMS_00001);
        messageInfo.setData(smsDto);
        // 设置需要加锁
        messageInfo.setExclusion(false);
        // 设置最大重试次数
        messageInfo.setMaxRetryCount(1);
        // 设置过期时间
        messageInfo.setExpiration(MqConstant.DELAY_EXPIRATION_S_10);
        mqService.sendMessage(messageInfo);
        return true;
    }
}
